package com.ops.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 * 统一处理系统中抛出的异常
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * 处理系统中的所有异常，转换为友好的错误页面
     * 
     * @param request HTTP请求
     * @param e 捕获的异常
     * @return 错误页面视图
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(HttpServletRequest request, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        
        // 区分业务异常和系统异常
        if (e instanceof BusinessException) {
            BusinessException be = (BusinessException) e;
            modelAndView.addObject("code", be.getCode());
            modelAndView.addObject("message", be.getMessage());
        } else {
            modelAndView.addObject("code", "500");
            modelAndView.addObject("message", "系统内部错误，请联系管理员");
        }
        
        modelAndView.addObject("url", request.getRequestURL());
        modelAndView.setViewName("error/error");
        return modelAndView;
    }
} 